import { _decorator, BlockInputEvents, Button, Component, director, instantiate, Label, Layout, Node, Prefab, resources, SpriteFrame, tween, UITransform, Vec3, view } from 'cc';
const { ccclass, property } = _decorator;

interface LevelConfig {
    title: string;
    baseScore: number;
    threshold: number;
    sceneName: string;
}

@ccclass('LevelSelectionPanel')
export class LevelSelectionPanel extends Component {
    // 预制体引用
    @property({ type: Prefab })
    private levelItemPrefab: Prefab = null!;

    @property(Prefab)
    rulesPopup: Prefab = null!;

    @property(Node)
    topPanel: Node = null!;         // 顶部栏容器

    // UI节点引用
    @property({ type: Node })
    private contentLayout: Node = null!;  // 布局容器

    @property({ type: Button })
    private backButton: Button = null!;

    // 动画参数
    private readonly ANIM_DURATION = 0.5;  // 动画持续时间
    private readonly ENTER_OFFSET = 1000; // 进入偏移量
    private readonly EXIT_OFFSET = -1000;  // 退出偏移量

    private _currentPopup: Node | null = null;
    private _maskNode: Node | null = null;

    // 关卡配置数据
    private levelConfigs: LevelConfig[] = [
        { title: "初级", baseScore: 100, threshold: 500, sceneName: "PrimaryScene" },
        { title: "中级", baseScore: 200, threshold: 1000, sceneName: "IntermediateScene" },
        { title: "高级", baseScore: 300, threshold: 1500, sceneName: "AdvancedScene" }
    ];

    // 生命周期方法
    onLoad() {
        this.initUI();
        this.playEnterAnimation();
    }

    // 初始化UI
    private initUI() {
         // 初始化顶部栏
         this.initTopPanel();

        this.generateLevelItems();
        this.setupButtonListeners();
        this.adjustLayout();
    }

    // 初始化顶部栏
        private initTopPanel() {
            const topPanelScript = this.topPanel.getComponent('TopPanel');
            topPanelScript.setTitle("");
    
            // 设置背景图
            resources.load('textures/top_bg', SpriteFrame, (err, spriteFrame) => {
                topPanelScript.setBackground(spriteFrame);
            });
    
            // 监听返回按钮事件
            topPanelScript.node.on('back-click', this.onBackButtonClick, this);
        }

    // 动态生成关卡选择项
    private generateLevelItems() {
        this.levelConfigs.forEach(config => {
            const item = instantiate(this.levelItemPrefab);
            this.contentLayout.addChild(item);

            // 设置文本内容
            this.setItemContent(item, config);
            
            // 绑定点击事件
            item.getComponent(Button)!.node.on(
                Button.EventType.CLICK, 
                () => this.onLevelSelected(config.sceneName)
            );
        });
    }

    // 设置选项内容
    private setItemContent(item: Node, config: LevelConfig) {
        const getLabel = (name: string) => 
            item.getChildByName(name)!.getComponent(Label)!;

        getLabel("Title").string = config.title;
        getLabel("BaseScore").string = `底分: ${config.baseScore}`;
        getLabel("Threshold").string = `铜钱门槛: ${config.threshold}`;
    }

    // 设置按钮监听
    private setupButtonListeners() {
        this.backButton.node.on(Button.EventType.CLICK, this.onBackButtonClick, this);
    }

    // 布局适配
    private adjustLayout() {
        const layout = this.contentLayout.getComponent(Layout)!;
        layout.updateLayout();
    }

    // 进入动画
    private playEnterAnimation() {
        const originalPos = this.node.position.clone();
        this.node.setPosition(originalPos.x + this.ENTER_OFFSET, originalPos.y, originalPos.z);
        this.node.scale = new Vec3(0.8, 0.8, 1);

        tween(this.node)
            .parallel(
            tween().to(this.ANIM_DURATION, { position: originalPos }, { easing: "sineOut" }),
            tween().to(this.ANIM_DURATION * 0.8, { scale: Vec3.ONE }, { easing: "backOut" })
        )
        .start();
    }

    // 退出动画
    private async playExitAnimation(): Promise<void> {
        return new Promise(resolve => {
            const targetPos = new Vec3(this.EXIT_OFFSET, this.node.position.y, this.node.position.z);
            
            tween(this.node)
                .to(this.ANIM_DURATION, { position: targetPos }, { easing: "sineIn" })
                .call(() => resolve())
                .start();
        });
    }

    // 关卡选择处理
    private async onLevelSelected(sceneName: string) {
        this.disableAllInteractions();
        await this.playExitAnimation();
        director.loadScene(sceneName);
    }

    // 返回按钮处理
    private async onBackButtonClick() {
        this.disableAllInteractions();
        await this.playExitAnimation();
        director.getScene().destroy();  // 销毁当前场景
        director.loadScene("LobbyScene"); // 修改为你的主场景名称
    }

    // 禁用交互
    private disableAllInteractions() {
        this.backButton.interactable = false;
        this.contentLayout.children.forEach(child => {
            child.getComponent(Button)!.interactable = false;
        });
    }

    onRulesClick() {
        cc.log(11)
        this.showPopup(this.rulesPopup);
        // this.showDevelopingPopup("功能开发中，敬请期待！");
    }

    // 统一弹窗显示逻辑
        private showPopup(popupPrefab: Prefab) {
            if (this._currentPopup) return;
    
            // 创建遮罩
            this.addMask();
    
            // 创建弹窗
            this._currentPopup = instantiate(popupPrefab);
            const popupLayer = this.node.getChildByName("PopupLayer");
            if (popupLayer) {
                this._currentPopup.parent = popupLayer;
                this._currentPopup.setPosition(0, 0); // 居中显示
            }
    
            // 绑定关闭事件
            const basePopup = this._currentPopup.getComponent('BasePopup');
            if (basePopup) {
                // 监听弹窗关闭事件
                basePopup.node.on('popup-closed', () => {
                    this.closeCurrentPopup();
                });
        
                // 如果存在关闭按钮，绑定点击事件
                if (basePopup.closeButton && basePopup.closeButton.node) {
                    basePopup.closeButton.node.on(Button.EventType.CLICK, () => {
                        basePopup.close();
                    });
                } else {
                    console.warn("当前弹窗没有关闭按钮");
                }
            } else {
                console.error("BasePopup 组件未找到");
            }
        }
    
        // 关闭弹窗
        private closeCurrentPopup() {
            if (this._currentPopup) {
                this._currentPopup.destroy();
                this._currentPopup = null;
            }
            if (this._maskNode) {
                this._maskNode.destroy();
                this._maskNode = null;
            }
        }
    
        // 添加遮罩
        private addMask() {
            const mask = new Node();
            const uiTransform = mask.addComponent(UITransform);
            uiTransform.contentSize = view.getVisibleSize();
            mask.addComponent(BlockInputEvents);
            
            const popupLayer = this.node.getChildByName("PopupLayer");
            if (popupLayer) {
                mask.parent = popupLayer;
                mask.setPosition(0, 0); // 全屏覆盖
            }
            this._maskNode = mask;
        }

}


